package com.whfc.safety.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whfc.base.param.AppFileExportParam;
import com.whfc.base.service.AppExportService;
import com.whfc.common.exception.BizException;
import com.whfc.common.file.FileHandler;
import com.whfc.common.file.FilePathConfig;
import com.whfc.common.file.properties.FileExpirationRules;
import com.whfc.common.result.PageData;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.*;
import com.whfc.fuum.service.SysDeptService;
import com.whfc.safety.dao.SafetyRectifyDetailsMapper;
import com.whfc.safety.dao.SafetyRectifyInfoMapper;
import com.whfc.safety.dto.SafetyCheckDTO;
import com.whfc.safety.dto.SafetyRectifyDTO;
import com.whfc.safety.entity.SafetyRectifyInfo;
import com.whfc.safety.param.SafetyRectifyAddParam;
import com.whfc.safety.param.SafetyRectifyEditParam;
import com.whfc.safety.service.SafetyRectifyService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.Date;
import java.util.List;

/**
 * @author: hw
 * @date: 2021-10-18 17:41
 * @description: 质量整改单
 */
@DubboService(interfaceClass = SafetyRectifyService.class, version = "1.0.0")
public class SafetyRectifyServiceImpl implements SafetyRectifyService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private final static String QUALITY_FILE_DESC = "安全整改通知单导出";

    private final static String HTML_TEMPLATE_PATH = "pdfTemp/SafetyRectifyTemp.html";

    private final static String PDF_CONFIG_PATH = "pdfConfig/config.json";

    @Autowired
    private SafetyRectifyInfoMapper safetyRectifyInfoMapper;

    @Autowired
    private SafetyRectifyDetailsMapper safetyRectifyDetailsMapper;

    @DubboReference(interfaceClass = SysDeptService.class, version = "1.0.0")
    private SysDeptService sysDeptService;

    @DubboReference(interfaceClass = AppExportService.class, version = "1.0.0")
    private AppExportService appExportService;

    @Autowired
    private FilePathConfig msFilePathConfig;

    @Autowired
    private FileHandler fileHandler;

    private JSONObject pdfConfig;
    
    @PostConstruct
    public void info() throws IOException {
        ClassPathResource resource = new ClassPathResource(PDF_CONFIG_PATH);
        InputStream templateFileInputStream = resource.getInputStream();
        String pdfConfigStr = new String(FileUtil.readData(templateFileInputStream));
        if (StringUtils.isNotEmpty(pdfConfigStr)) {
            pdfConfig = JSONObject.parseObject(pdfConfigStr);
        }
    }

    @Override
    public PageData<SafetyRectifyDTO> list(Integer deptId, Date startTime, Date endTime, Integer pageNum, Integer pageSize) throws BizException {
        logger.info("整改通知单列表,deptId：{},startTime：{},endTime：{},pageNum：{},pageSize：{}", deptId, startTime, endTime, pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<SafetyRectifyDTO> list = safetyRectifyInfoMapper.selectByDeptId(deptId, startTime, endTime);
        for (SafetyRectifyDTO v : list) {
            Integer questionNum = safetyRectifyDetailsMapper.selectCountByRectifyId(v.getRectifyId());
            v.setQuestionNum(questionNum);
        }
        PageHelper.clearPage();
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    public PageData<SafetyCheckDTO> details(Integer rectifyId, Integer pageNum, Integer pageSize) throws BizException {
        logger.info("整改通知单详情,rectifyId：{},pageNum：{},pageSize：{}", rectifyId, pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<SafetyCheckDTO> list = safetyRectifyDetailsMapper.selectByRectifyId(rectifyId);
        PageHelper.clearPage();
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    public void add(SafetyRectifyAddParam param) throws BizException {
        logger.info("添加整改通知单,param:{}", param);
        SafetyRectifyInfo record = new SafetyRectifyInfo();
        record.setQuestionNum(param.getCheckIds().size());
        BeanUtils.copyProperties(param, record);
        safetyRectifyInfoMapper.insertSelective(record);
        safetyRectifyDetailsMapper.insertAll(record.getId(), param.getCheckIds());
    }

    @Override
    public void edit(SafetyRectifyEditParam param) throws BizException {
        SafetyRectifyInfo record = safetyRectifyInfoMapper.selectByPrimaryKey(param.getRectifyId());
        if (record == null) {
            throw new BizException(ResultEnum.NOT_FOUND.getCode(), "未找到该整改单信息");
        }
        safetyRectifyDetailsMapper.delByRectifyId(record.getId());
        BeanUtils.copyProperties(param, record);
        safetyRectifyInfoMapper.updateByPrimaryKeySelective(record);
        safetyRectifyDetailsMapper.insertAll(record.getId(), param.getCheckIds());
    }

    @Override
    public void del(Integer rectifyId) throws BizException {
        logger.info("删除整改通知单,rectifyId:{}", rectifyId);
        safetyRectifyDetailsMapper.delByRectifyId(rectifyId);
        safetyRectifyInfoMapper.del(rectifyId);
    }

    @Override
    public void export(Integer rectifyId) throws BizException {
        logger.info("导出整改通知单,rectifyId:{}", rectifyId);
        SafetyRectifyInfo rectifyInfo = safetyRectifyInfoMapper.selectByPrimaryKey(rectifyId);
        String fileDesc = QUALITY_FILE_DESC;
        String fileName = RandomUtil.getRandomFileName();
        String suffix = "pdf";
        AppFileExportParam fileExport = new AppFileExportParam();
        fileExport.setDeptId(rectifyInfo.getDeptId());
        fileExport.setFileName(fileName);
        fileExport.setFileFormat(suffix.toUpperCase());
        fileExport.setFileState(0);
        fileExport.setFileDesc(fileDesc);
        Integer id = appExportService.install(fileExport);
        fileExport.setId(id);
        String companyName = null;
        String footer = null;
        String header = null;
        if (pdfConfig.containsKey(rectifyInfo.getDeptId().toString())) {
            JSONObject config = pdfConfig.getJSONObject(rectifyInfo.getDeptId().toString());
            companyName = config.getString("companyName");
            footer = config.getString("footer");
            header = config.getString("header");
        }
        String deptName = sysDeptService.getDeptName(rectifyInfo.getDeptId());
        String timeStr = DateUtil.formatDate(rectifyInfo.getCreateTime(), DateUtil.DATE_FORMAT);
        String[] times = timeStr.split("-");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("companyName", companyName);
        jsonObject.put("deptName", deptName);
        jsonObject.put("corpName", rectifyInfo.getCorpName());
        jsonObject.put("years", times[0]);
        jsonObject.put("month", times[1]);
        jsonObject.put("day", times[2]);
        List<SafetyCheckDTO> list = safetyRectifyDetailsMapper.selectByRectifyId(rectifyId);
        jsonObject.put("checkList", JSONArray.parseArray(JSONUtil.toString(list)));
        ClassPathResource resource = new ClassPathResource(HTML_TEMPLATE_PATH);
        String html;
        try {
            logger.info("开始生成文件");
            InputStream templateFileInputStream = resource.getInputStream();
            File tempFile = FileUtil.copyTemplateFile(templateFileInputStream);
            html = HtmlUtil.freeMarkerRender(jsonObject, tempFile);
            logger.debug("html:{}", html);
            ByteArrayOutputStream arrayOutputStream = ItextPdfUtil.htmlToPdf(html, header, footer);
            InputStream is = new ByteArrayInputStream(arrayOutputStream.toByteArray());
            templateFileInputStream.close();
            logger.info("文件生成完成,开始上传文件");
            String path = msFilePathConfig.getFilePath("quality/export", fileName, suffix);
            String upload = fileHandler.upload(path, is, FileExpirationRules.DAYS_7);
            fileExport.setFileUrl(upload);
            fileExport.setFileState(1);
            appExportService.update(fileExport);
        } catch (Exception e) {
            logger.error("质量pdf导出异常", e);
        }
    }

    @Transactional
    @Override
    public void deleteBatch(List<Integer> idList) {
        if(CollectionUtils.isEmpty(idList)){
            return;
        }
        safetyRectifyInfoMapper.deleteBatch(idList);
        safetyRectifyDetailsMapper.deleteBatchByRectifyId(idList);
    }
}
